<?php

namespace App\Api\Controllers\v1;

use App\Admin\Helper;
use App\Http\Controllers\ApiController;
use App\Http\Response\ApiResponse;
use App\Models\AgentMoney;
use App\Models\AgentUser;

use App\Models\Area;
use App\Models\CashOrder;
use App\Models\GoodOrder;
use App\Models\OrderCommission;
use App\Models\ServiceOrder;
use App\Models\ShopMoney;
use App\Models\ShopUser;
use App\Models\User;
use App\Models\UserAmount;
use App\Models\UserCard;
use App\Models\Worker;
use App\Models\WorkerMoney;
use hg\apidoc\annotation as Apidoc;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/**
 * 管理台接口
 * @Apidoc\Group("user")
 */
class ManagerController extends ApiController
{
    /**
     * 获取代理商资料信息
     * @Apidoc\Url("/api/v1/manager/agent")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("detail",ref="App\Models\AgentUser\getDetail")
     */
    public function agent(): ApiResponse
    {
        $user_id = $this->user_id;
        $detail = AgentUser::getDetail($user_id);
//        if ($detail){
//            $detail->shopList = ShopUser::query()->select(["id","name"])->where("agent_id",$detail->id)->get();
//        }
        $data['detail'] = $detail;
        return $this->response()->data($data);
    }

    /**
     * 获取门店资料信息
     * @Apidoc\Url("/api/v1/manager/shop")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("detail",ref="App\Models\ShopUser\getDetail")
     */
    public function shop(): ApiResponse
    {
        $user_id = $this->user_id;
        $detail = ShopUser::getDetail($user_id);
        $data['detail'] = $detail;
        return $this->response()->data($data);
    }

    /**
     * 获取技师师傅资料信息
     * @Apidoc\Url("/api/v1/manager/worker")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("detail",ref="App\Models\Worker\getDetail")
     */
    public function worker(): ApiResponse
    {
        $user_id = $this->user_id;
        $detail = Worker::getDetail($user_id);
        $data['detail'] = $detail;
        return $this->response()->data($data);
    }

    /**
     * 获取管理台服务收入
     * @Apidoc\Url("/api/v1/manager/services")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("type",type="int", default="0", desc="类型:0=代理商,1=门店,2=技师师傅,3=推广收益")
     * @Apidoc\Query("agent_id",type="int", default="0", desc="代理商ID,代理商的参数")
     * @Apidoc\Query("time",type="string", default="0", desc="时间查询:0=今天,1=昨天,2=本月内,3=总的, [Y-m-d - Y-m-d]=自定义")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned("order_count", type="int", default="待接单数量", default="0")
     * @Apidoc\Returned("moneys", type="int", default="收入", default="0")
     * @Apidoc\Returned("items", type="array", default="收入列表", default="0")
     */
    public function services(Request $request): ApiResponse
    {
        $user_id = $this->user_id;
        $type = $request->get("type");
        $time = $request->get("time");
        $pageSize = $request->get("pageSize",10);
        $where = [];
        $timeRange = Helper::getTimeRange($time);
        $list = [];
        $fields = ['id','type','shop_id','worker_id','agent_id','order_id','amount','service_id','service_name','created_at','is_settle'];
        $model = OrderCommission::with(['shop'=>function($query){
            $query->select(["id","name"]);
        }])->where('type',0)->select($fields)->where("is_settle","<>",2);
        $shopIds = [];
        switch ($type){
            case 1:
                //门店
                $detail = ShopUser::getDetail($user_id);
                if ($detail){
                    $where['shop_id'] = $detail->id;
                    $model = $model->where($where)->when($timeRange,function ($query,$value){
                        $query->whereBetween("created_at", $value);
                    })->addSelect('shop_money as money');
                    $list = $model->paginate($pageSize);
                }
                break;
            case 2:
                $detail = Worker::getDetail($user_id);
                if ($detail){
                    $where['worker_id'] = $detail->id;
                    $model = $model->where($where)->when($timeRange,function ($query,$value){
                        $query->whereBetween("created_at", $value);
                    })->addSelect('worker_money as money');
                    $list = $model->paginate($pageSize);
                }
                break;
            case 3:
                $where1 = function ($query) use ($where,$user_id, $timeRange) {
                    $query->where($where)->where("top_id",$user_id)
                        ->when($timeRange,function ($query,$value){
                            $query->whereBetween("created_at", $value);
                        });
                };
                $where2 = function ($query) use ($where,$user_id, $timeRange) {
                    $query->where($where)->where("top_top_id",$user_id)
                        ->when($timeRange,function ($query,$value){
                            $query->whereBetween("created_at", $value);
                        });
                };
                $query1 = OrderCommission::select($fields)
                    ->addSelect('card_title')
                    ->addSelect('top_money as money')
                    ->where("is_settle","<>",2)
                    ->having("money",">",0)
                    ->where($where1);
                $model = $model->addSelect('card_title')->addSelect('top_top_money as money')
                    ->where($where2)
                    ->having("money",">",0)
                    ->unionAll($query1);
                $list = $model->paginate($pageSize);
                break;
            default:
                //代理商
                $detail = AgentUser::getDetail($user_id);
                if ($detail){
                    $agent_id = $detail->id;
                    $shopIds = ShopUser::query()->where("agent_id",$agent_id)->pluck("id");
                    $model = $model
                        ->addSelect(DB::raw("sum(agent_money) as money"))
                        ->addSelect(DB::raw("sum(amount) as amount"))
                        ->where("agent_id",$agent_id)
                        ->when($timeRange,function ($query,$value){
                            $query->whereBetween("created_at", $value);
                        });
                    $list = $model->groupBy("shop_id")->having("money",">",0)->get();
                }
                break;
        }
        $settles = ['待结算','已结算'];
        if ($type==3){
            foreach ($list as $item){
                $item->created_text = Carbon::parse($item->created_at)->format("Y年m月d日 H时i分");
                $item->settle_text = $settles[$item->is_settle];
                $item->money = floatval($item->money);
                if ($item->type==2){
                    $item->name = "购买【{$item->card_title}】";
                }elseif ($item->type==0){
                    $item->name = "洗车【{$item->service_name}】";
                }else{
                    $item->name = "购买商品";
                }
            }
            $data['price'] = $model->sum("money");
            $data['items'] = $list->items();
            $data['total'] = $list->total();
            $data['lastPage'] = $list->lastPage();
        }else{
            $data['order_count'] = ServiceOrder::query()->when(!$type,function ($query) use ($shopIds) {
                $query->where("shop_id",">",0)->whereIn("shop_id",$shopIds);
            })->when($where,function ($query,$value){
                $query->where($value);
            })->when($timeRange,function ($query,$value){
                $query->whereBetween("order_time", $value);
            })->count();

            $data['moneys'] = $model->get()->sum(function ($item){
                return $item->money;
            });
            if ($list){
                foreach ($list as $item){
                    $item->created_text = Carbon::parse($item->created_at)->format("Y年m月d日 H时i分");
                    $item->settle_text = $settles[$item->is_settle];
                    $item->money = floatval($item->money);
                }
            }

            if($type==0){
                $data['items'] = $list;
                $data['lastPage'] = $list?1:0;
                $data['total'] = count($list);
            }else{
                $data['items'] = $list?$list->items():[];
                $data['total'] = $list?$list->total():0;
                $data['lastPage'] = $list?$list->lastPage():0;
            }
        }
        return $this->response()->data($data);
    }

    /**
     * 获取管理台商城订单收入
     * @Apidoc\Url("/api/v1/manager/goods")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("type",type="int", default="0", desc="类型:0=代理商,1=门店")
     * @Apidoc\Query("time",type="string", default="0", desc="时间查询:0=今天,1=昨天,2=本月内,3=总的, [Y-m-d - Y-m-d]=自定义")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned("items", type="array", default="收入列表", default="")
     */
    public function goods(Request $request): ApiResponse
    {
        $user_id = $this->user_id;
        $type = $request->get("type");
        $time = $request->get("time");
        $pageSize = $request->get("pageSize",10);
        $timeRange = Helper::getTimeRange($time);
        $list = [];
        $model = OrderCommission::query()
            ->select(['id','order_id','amount','created_at','is_settle'])
            ->where("type",1)
            ->where("is_settle","<>",2);
        if ($type){
            //门店
            $detail = ShopUser::getDetail($user_id);
            if ($detail){
                $list = $model->when($timeRange,function ($query,$value){
                    $query->whereBetween("created_at", $value);
                })->addSelect('shop_money as money')->where("shop_id",$detail->id)->paginate($pageSize);
            }
        }else{
            //代理商
            $detail = AgentUser::getDetail($user_id);
            $model = $model->when($timeRange,function ($query,$value){
                $query->whereBetween("created_at", $value);
            });
            if ($detail){
                $list = $model->where("agent_id",$detail->id) ->addSelect('agent_money as money')->paginate($pageSize);
            }
        }
        $settles = ['待结算','已结算'];
        foreach ($list as $item){
            $item->created_text = Carbon::parse($item->created_at)->format("Y年m月d日 H时i分");
            $item->settle_text = $settles[$item->is_settle];
            $item->money = floatval($item->money);
            $item->remark = "商品订单分成收入";
        }
        if ($list){
            $data['items'] = $list->items();
            $data['total'] = $list->total();
            $data['lastPage'] = $list->lastPage();
        }else{
            $data['items'] = [];
            $data['total'] = 0;
            $data['lastPage'] = 0;
        }

        return $this->response()->data($data);
    }

    /**
     * 获取管理台支出记录
     * @Apidoc\Url("/api/v1/manager/expends")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("type",type="int", default="0", desc="类型:0=代理商,1=门店,2=技师师傅,3=推广收益")
     * @Apidoc\Query("time",type="string", default="0", desc="时间查询:0=今天,1=昨天,2=本月内,3=总的, [Y-m-d - Y-m-d]=自定义")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="App\Models\AgentUser\getDetail")
     */
    public function expends(Request $request): ApiResponse
    {
        $user_id = $this->user_id;
        $type = $request->get("type");
        $time = $request->get("time");
        $pageSize = $request->get("pageSize",10);
        $where = [];
        $timeRange = Helper::getTimeRange($time);
        switch ($type){
            case 1:
                //门店
                $model = new ShopMoney();
                $detail = ShopUser::getDetail($user_id);
                if ($detail){
                    $where['shop_id'] = $detail->id;
                }
                break;
            case 2:
                $model = new WorkerMoney();
                $detail = Worker::getDetail($user_id);
                if ($detail){
                    $where['worker_id'] = $detail->id;
                }
                break;
            case 3:
                $model = new UserAmount();
                $where['user_id'] = $this->user_id;
                break;
            default:
                //代理商
                $model = new AgentMoney();
                $detail = AgentUser::getDetail($user_id);
                if ($detail){
                    $where['agent_id'] = $detail->id;
                }
                break;
        }
        $list = $model->select(['id','money','remark','created_at'])->where("money","<",0)->where($where)->when($timeRange,function ($query,$value){
            $query->whereBetween("created_at", $value);
        })->paginate($pageSize);
        foreach ($list as $item){
            $item->created_text = Carbon::parse($item->created_at)->format("Y年m月d日 H时i分");
            $item->money = floatval($item->money);
        }
        if ($type==3){
            $data['price'] = $model->where($where)->where("money","<",0)->sum("money");
        }
        $data['items'] = $list->items();
        $data['total'] = $list->total();
        $data['lastPage'] = $list->lastPage();
        return $this->response()->data($data);
    }

    /**
     * 提现申请
     * @Apidoc\Url("/api/v1/manager/cash")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("type",type="int", default="0", desc="类型:0=店主提现,1=员工提现,2=代理商提现,3=用户提现(推广收益)")
     * @Apidoc\Param("bank_id",type="int", default="0", desc="用户银行卡ID")
     * @Apidoc\Param("amount",type="string", default="0", desc="提现金额")
     */
    public function cash(Request $request){
        $type = $request->post("type",0);
        $bank_id = $request->post("bank_id",0);
        $user_id = $this->user_id;
        if ($type==0){
            $model = ShopUser::whereUserId($user_id)->first();
        }elseif ($type==1){
            $model = Worker::whereUserId($user_id)->first();
        }elseif ($type==2){
            $model = AgentUser::whereUserId($user_id)->first();
        }else{
            $model = User::whereId($user_id)->first();
        }
        CashOrder::cash($type,$model, $bank_id);
    }

    /**
     * 提现记录
     * @Apidoc\Url("/api/v1/manager/cashLogs")
     * @Apidoc\Method("GET")
     * @Apidoc\Query("type",type="int", default="0", desc="类型:0=店主提现,1=员工提现,2=代理商提现")
     * @Apidoc\Query(ref="queryPage")
     * @Apidoc\Returned(ref="listResult")
     */
    public function cashLogs(): ApiResponse
    {
        $data = CashOrder::getList($this->user_id);
        return $this->response()->data($data);
    }

    /**
     * 师傅接单今日业绩排行
     * @Apidoc\Url("/api/v1/manager/ranks")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("items", type="array", default="排行列表", default="")
     */
    public function ranks(): ApiResponse
    {
        $query = DB::table(function ($query){
                $query->from("service_orders")
                    ->select([
                        "service_orders.id","service_orders.worker_id","service_orders.status",
                        "users.nickname","users.avatar","users.id as user_id"
                    ])
                    ->addSelect(DB::raw("SUM(service_orders.amount) as money"))
                    ->join("worker","worker.id","=","service_orders.worker_id")
                    ->join("users","users.id","=","worker.user_id")
                    ->where("service_orders.worker_id",">",0)
                    ->where("service_orders.status","<",4)
                    ->whereDate("service_orders.created_at",now())
                    ->groupBy("service_orders.worker_id")
                    ->having("money",">",0)
                    ->orderByDesc("money")
                    ->orderByDesc("users.id");
            })
            ->select(["user_id","worker_id","status","nickname","avatar","money"])
            ->addSelect(DB::raw("if(@rank,@rank := @rank +1,@rank := 1) as rank"));
        $data["items"] = $query->limit(100)->get();
        $data["user"] = $query->where("user_id",$this->user_id)->first();
        if ($data["user"]){
            $data["user"]->avatar = cdn_url($data["user"]->avatar);
        }
        foreach ($data["items"] as $item){
            $item->avatar = cdn_url($item->avatar);
        }
        return $this->response()->data($data);
    }
}
